<template>
  <div class="wallet-page">
    <!-- 导航栏 -->
    <van-nav-bar
      title="钱包中心"
      left-arrow
      @click-left="onClickLeft"
    />

    <!-- 余额展示 -->
    <div class="balance-section">
      <div class="balance-label">余额(元)</div>
      <div class="balance-amount">{{ userInfo.balance || '0.00' }}</div>
      <div class="action-buttons">
        <van-button plain type="danger" size="small" @click="showWithdraw">提现</van-button>
        <van-button type="danger" size="small" @click="showRecharge">充值</van-button>
      </div>
    </div>

    <!-- 交易记录 -->
    <div class="transaction-section">
      <div class="section-header">
        <span>流水明细</span>
        <van-dropdown-menu>
          <van-dropdown-item v-model="timeRange" :options="timeOptions" />
          <van-dropdown-item v-model="filterType" :options="filterOptions" />
        </van-dropdown-menu>
      </div>

      <div class="transaction-list">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <div class="transaction-item" v-for="item in transactionList" :key="item.id">
            <div class="item-left">
              <van-icon :name="getTransactionIcon(item.type)" :class="getIconClass(item.type)" />
              <div class="item-info">
                <div class="item-title">{{ item.title }}</div>
                <div class="item-time">{{ item.time }}</div>
              </div>
            </div>
            <div :class="['item-amount', item.amount > 0 ? 'income' : 'expense']">
              {{ item.amount > 0 ? '+' : '' }}{{ item.amount }}
            </div>
          </div>
        </van-list>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { getWallet as getWalletApi, getWalletDetail } from '@/api/user/wallet'
import { getTransactionList } from '@/api/user/transaction'

const router = useRouter()
const userInfo = ref({})

// 筛选选项
const timeRange = ref(0)
const filterType = ref(0)
const timeOptions = [
  { text: '本月', value: 0 },
  { text: '上月', value: 1 },
  { text: '近三月', value: 2 }
]
const filterOptions = [
  { text: '全部明细', value: 0 },
  { text: '充值', value: 2 },
  { text: '提现', value: -1 },
  { text: '支付', value: -2 },
  { text: '退款', value: 1 }
]

// 列表加载相关
const loading = ref(false)
const finished = ref(false)
const transactionList = ref([])
const total = ref(0)
const params = ref({ 
  user_id: 0,
  page: 0,
  pageSize: 10,
  timeRange: 0,
  filterType: 0
})

//获取钱包
const fetchWalletInfo = async () => {
  const res = await getWalletApi(userInfo.value.id)
  if (res.code === 200) {
    userInfo.value.balance = res.data.balance
  }
}

// 获取用户信息
onMounted(() => {
  const userStr = sessionStorage.getItem('user')
  if (userStr) {
    userInfo.value = JSON.parse(userStr)
    params.value.user_id = userInfo.value.id
    fetchWalletInfo()
  }
})

// 返回上一页
const onClickLeft = () => {
  router.back()
}

// 加载更多
const onLoad = async () => {
  loading.value = true
  params.value.page++
  params.value.timeRange = timeRange.value
  params.value.filterType = filterType.value
  
  try {
    const res = await getTransactionList(params.value)
    if (res.code === 200) {
      // 转换数据结构
      const newList = res.data.list.map(item => ({
        id: item.id,
        type: getTransactionType(item.transaction_type),
        title: item.remark,
        time: item.created_time,
        amount: item.amount
      }))
      
      // 如果是第一页，直接替换数据
      if (params.value.page === 1) {
        transactionList.value = newList
      } else {
        // 否则追加数据
        transactionList.value = [...transactionList.value, ...newList]
      }
      
      total.value = res.data.total
      // 判断是否加载完成
      finished.value = transactionList.value.length >= total.value
    }
  } catch (error) {
    showToast('加载失败')
  } finally {
    loading.value = false
  }
}

// 新增：根据交易类型返回对应的type
const getTransactionType = (transactionType) => {
  const typeMap = {
    1: 'refund',     // 退款
    2: 'recharge',   // 充值
    '-1': 'withdraw', // 提现
    '-2': 'payment'  // 支付
  }
  return typeMap[transactionType] || 'payment'
}

// 监听筛选条件变化
watch([timeRange, filterType], () => {
  params.value.page = 0
  finished.value = false
  onLoad()
})

// 获取交易图标
const getTransactionIcon = (type) => {
  const iconMap = {
    recharge: 'balance-pay',
    payment: 'shopping-cart-o',
    refund: 'refund-o',
    withdraw: 'cash-back-record'
  }
  return iconMap[type] || 'records'
}

// 获取图标样式
const getIconClass = (type) => {
  return `transaction-icon ${type}`
}

// 操作按钮事件
const showDeposit = () => {
  showToast('保证金功能开发中')
}

const showWithdraw = () => {
  showToast('提现功能开发中')
}

const showRecharge = () => {
  showToast('充值功能开发中')
}
</script>

<style scoped>
.wallet-page {
  min-height: 100vh;
  background: #f7f8fa;
}

.balance-section {
  background: #fff;
  padding: 24px 16px;
  text-align: center;
}

.balance-label {
  color: #969799;
  font-size: 14px;
}

.balance-amount {
  font-size: 32px;
  font-weight: bold;
  margin: 8px 0 16px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 12px;
}

.transaction-section {
  margin-top: 12px;
  background: #fff;
}

.section-header {
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f5f5f5;
}

.transaction-list {
  padding: 0 16px;
}

.transaction-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #f5f5f5;
}

.item-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.transaction-icon {
  font-size: 24px;
  padding: 8px;
  border-radius: 8px;
}

.recharge {
  background: #e8f3ff;
  color: #1989fa;
}

.payment {
  background: #fef0f0;
  color: #f56c6c;
}

.refund {
  background: #f0f9eb;
  color: #67c23a;
}

.withdraw {
  background: #f4f4f5;
  color: #909399;
}

.item-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.item-title {
  font-size: 14px;
}

.item-time {
  font-size: 12px;
  color: #969799;
}

.item-amount {
  font-size: 16px;
  font-weight: 500;
}

.income {
  color: #67c23a;
}

.expense {
  color: #f56c6c;
}

:deep(.van-dropdown-menu) {
  height: 32px;
  flex-shrink: 0;
  min-width: 120px;
}

:deep(.van-dropdown-menu__bar) {
  height: 32px;
  background: transparent;
}

:deep(.van-dropdown-menu__item) {
  justify-content: flex-end;
  padding: 0 8px;
}

:deep(.van-dropdown-menu__title) {
  font-size: 14px;
  color: #666;
}
</style> 